package com.lq.dubbo.rocketmq.shop.mq;

import com.alibaba.fastjson.JSON;
import com.lq.dubbo.rocketmq.shop.api.IUserService;
import com.lq.dubbo.rocketmq.shop.constant.ShopCode;
import com.lq.dubbo.rocketmq.shop.entity.MQEntity;
import com.lq.dubbo.rocketmq.shop.shop_pojo.TradeUserMoneyLog;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;

/**
 * @program: dubborocketmqshop
 * @description: 消息监听
 * 因为订单回退,用户,商品,订单,优惠券系统登都需要监听做相应设置,所以messageModel(消费模式)设置为广播消费模式
 * @author: LQ
 * @create: 2021-06-24 16:25
 */
@Slf4j
@Component
@RocketMQMessageListener(topic = "${mq.order.topic}", consumerGroup = "${mq.order.consumer.group.name}", messageModel = MessageModel.BROADCASTING)
public class CancelMqListener implements RocketMQListener<MessageExt> {

    @Autowired
    private IUserService userService;

    // MessageExt 继承Message 有消息ID
    @Override
    public void onMessage(MessageExt messageExt) {
        String body = null;
        MQEntity mqEntity = null;
        // 1.解析消息
        try {
            body = new String(messageExt.getBody(), "UTF-8");
            mqEntity = JSON.parseObject(body, MQEntity.class);
            log.info("user-service:接收消息成功");
            // 2.调用业务层进行余额修改
            if (mqEntity.getUserMoney() != null && mqEntity.getUserMoney().compareTo(BigDecimal.ZERO) > 0) {
                TradeUserMoneyLog userMoneyLog = new TradeUserMoneyLog();
                userMoneyLog.setUseMoney(mqEntity.getUserMoney());
                userMoneyLog.setMoneyLogType(ShopCode.SHOP_USER_MONEY_REFUND.getCode());
                userMoneyLog.setUserId(mqEntity.getUserId());
                userMoneyLog.setOrderId(mqEntity.getOrderId());
                userService.updateMoneyPaid(userMoneyLog);
                log.info("余额回退成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("余额回退失败!" );
        }
    }
}
